import 'dart:async';

import 'package:faker/models/rss.dart';
import 'package:faker/service/baseservice.dart';
import 'package:http/http.dart' as http;
import 'package:shared_preferences/shared_preferences.dart';
import 'package:webfeed/webfeed.dart';

class RssApi implements BaseServices {
  static final RssApi _instance = RssApi._internal();
  factory RssApi() => _instance;
  RssApi._internal();

  String domain;

  String api;

  void setAppConfig(appConfig) async {
    final prefs = await SharedPreferences.getInstance();
    String server = prefs.getString('server');
    domain = server != null ? server : appConfig["url_domain"];
    api = appConfig["url_api"];
  }

  void setServer(server) {
    domain = server;
  }

  @override
  Future<RssBean> getRss(name) async {
    try {
      var response = await http.get("$domain$name" + ".rss");
      if (response.statusCode == 200) {
        RssFeed rssFeed = new RssFeed.parse(response.body);
        return RssBean(
          title: rssFeed.title,
          author: rssFeed.author,
          description: rssFeed.description,
          link: rssFeed.link,
          items: rssFeed.items,
          image: rssFeed.image,
          cloud: rssFeed.cloud,
          categories: rssFeed.categories,
          skipDays: rssFeed.skipDays,
          skipHours: rssFeed.skipHours,
          lastBuildDate: rssFeed.lastBuildDate,
          language: rssFeed.language,
          generator: rssFeed.generator,
          copyright: rssFeed.copyright,
          docs: rssFeed.docs,
          managingEditor: rssFeed.managingEditor,
          rating: rssFeed.rating,
          webMaster: rssFeed.webMaster,
          ttl: rssFeed.ttl,
          dc: rssFeed.dc,
        );
      }
    } catch (e) {
      throw e;
    }
  }
}
